package com.vpen.netty.demo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/14 10:58
 */
public class NettyServer {


    public static void main(String[] args) {

        // 创建两个线程组，两个都是无限循环
        // bossGroup只负责连接，workerGroup负责业务逻辑
        //  默认线程数是 cpu核心 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 创建服务启动对象，配置参数
        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            //给我们的workerGroup的eventLoop的对应管道设置处理器
            bootstrap.group(bossGroup, workerGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)//使用NioServerSocketChannel作为服务器通道实现;
                    .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列等待连接的个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 创建通道初始化对象

                        // 给pipeline设置处理器，就是设置业务逻辑
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 通过channel拿到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 在管道的最后添加处理器,需要我们继承netty规定好的处理器适配器ChannelInboundHandlerAdapter
                            pipeline.addLast(new HelloWorldServerHandler());

                        }
                    });

            // 绑定端口并同步，生成一个Future对象
            ChannelFuture future = bootstrap.bind(6666).sync();
            // 关闭通道进行监听
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

}
